<template>
  <BasicModal v-bind="$attrs" title="编辑" @register="registerModal" @ok="handleSubmit">
      <BasicForm @register="registerForm">
        <template #trainTime="{ model, field }">
          <RangePicker 
            value-format="YYYY-MM-DD"
            style="width: 100%" 
            :disabled-date="disabledDate" 
            v-model:value="model[field]" 
           />
        </template>
      </BasicForm>
  </BasicModal>
</template>

<script lang="ts" setup>
import { RangePicker } from 'ant-design-vue'
import { computed, defineComponent, ref, unref } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, useForm } from '@/components/Form'
import type { Dayjs } from 'dayjs'
import dayjs from 'dayjs'
import { updateTrainingNumber } from '@/api/train/detail.ts'

const props = defineProps({
  trainingNumberId:{
    type: [Number,String],
    default: ''
  }
})

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: [
    {
      field: '[trainingStartTime, trainingEndTime]',
      label: '培训时间：',
      component: 'RangePicker',
      slot: 'trainTime',
      rules: [
        {
          required: true,
          message: '请选择培训时间',
        },
      ],
    },
  ],
  showActionButtonGroup: false,
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields()
  setModalProps({ confirmLoading: false })
  setFieldsValue({
    ...data,
  })
})

// 禁用时间
function disabledDate(current: Dayjs) {
  return current && current < dayjs().subtract(1, 'day'); // 可选今天以及以后
//  return current && current < dayjs().endOf('day'); // 可选明天及以后
}

const emit = defineEmits(['success', 'register'])
async function handleSubmit() {
    const values = await validate()
    try {
      setModalProps({ confirmLoading: true })
      const { trainingStartTime,trainingEndTime } = values
      let params = {
        trainingNumberId: props.trainingNumberId,
        trainingStartTime,
        trainingEndTime,
      }
      await updateTrainingNumber(params)
      emit('success', values)
      closeModal()
    } finally {
      setModalProps({ confirmLoading: false })
      setModalProps({ confirmLoading: false })
    }
  }
</script>